package com.chey.controller;

import com.chey.dao.UpViewDao;
import com.chey.domain.ResponseData;
import com.chey.domain.UpView;
import com.chey.domain.User;
import com.chey.domain.UserSecurity;
import com.chey.service.RoleService;
import com.chey.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Autowired
     private RoleService service;
    @Autowired
    private UpViewDao Viewdao;

    @Autowired
    private RedisCache redisCache;

    @RequestMapping("/index") //登录成功访问的接口
    public ResponseData hello(@AuthenticationPrincipal UserDetails userDetails){
        System.out.println("userDetails:"+userDetails); //输出登录用户信息
        ResponseData rs=new ResponseData();
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        List<String> authoritiesList = new ArrayList<>();

        // 将 authorities 中的元素逐个添加到 authoritiesList 中
        for (GrantedAuthority authority : authorities) {
            authoritiesList.add(authority.toString());
        }
//        String token = JwtUtil.createJWT(userDetails.getUsername());
        String token = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        redisCache.setCacheList("login:token:"+token,authoritiesList);
        redisCache.expire("login:token:"+token,5L, TimeUnit.MINUTES);

        if(userDetails instanceof UserSecurity){
            UserSecurity userSecurity= (UserSecurity) userDetails;
            User user=userSecurity.getUser();
            List<UpView> upViews = Viewdao.selectByUid(user.getId());



            return new ResponseData(200,"登录成功",upViews,token);

        }

        return null;
    }

//用于达到会话的最大值时 提示账户被其他人登录
    @GetMapping("/sessionOut")
    public ResponseData logout(){
        System.out.println("test");
        return new ResponseData(200,"ReLogin","账户在其他地方登录");
    }
}
